package com.local.es.controller;

import com.local.es.pojo.Goods;
import com.local.es.pojo.GoodsESDoc;
import com.local.es.pojo.GoodsSearchParam;
import com.local.es.service.GoodsService;
import com.local.es.utils.PageResultUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${rabbitmqs.es-goods-exchange}")
    private String esGoodsExchange;

    @Value("${rabbitmqs.es-goods-update-routing-key}")
    private String esGoodsUpdateRoutingKey;

    @Value("${rabbitmqs.es-goods-delete-routing-key}")
    private String esGoodsDeleteRoutingKey;

    /**
     * 初始化es_goods索引库：建立es_goods索引库，并将mysql中goods表的数据同步到es_goods索引库
     * @param page
     * @return
     */
    @GetMapping("/es/init/page/{page}")
    @ResponseBody
    public String index(@PathVariable("page") Integer page) {
        Integer resultCount = goodsService.initESData(page);
        return resultCount.toString();
    }


    /**
     * 通过关键词、价格区间搜索
     * http://127.0.0.1:8080/goods/search?keyword=小米&page=1&limit=10&minPrice=100&maxPrice=2000
     * @param param
     * @return
     */
    @GetMapping("/search")
    @ResponseBody
    public List<GoodsESDoc> search(GoodsSearchParam param) {
        Integer page = param.getPage();
        Integer limit = param.getLimit();
        page = (Objects.nonNull(page) && page >= 1) ? page : 1;
        limit = (Objects.nonNull(limit) && limit >= 1) ? limit : 10;
        param.setPage(page);
        param.setLimit(limit);

        PageResultUtil<GoodsESDoc> goodsESDocPageResultUtil = goodsService.searchES(param);
        List<GoodsESDoc> list = goodsESDocPageResultUtil.getList();
        System.out.println("总数："+goodsESDocPageResultUtil.getTotalCount());
        for (GoodsESDoc goodsESDoc : list) {
            System.out.println(goodsESDoc.toString());
        }

        return list;
    }


    /**
     * 通过拼音、字母的关键词得到搜索建议提示词，如：输入“xm”得到“小米”的提示
     * http://127.0.0.1:8080/goods/searchSuggestion/h
     * http://127.0.0.1:8080/goods/searchSuggestion/xm
     * @param keyword
     * @return
     */
    @GetMapping("/searchSuggestion/{keyword}")
    @ResponseBody
    public List<String> searchSuggestion(@PathVariable("keyword") String keyword) {
        List<String> suggestionList = goodsService.searchSuggestion(keyword);
        for (String s : suggestionList) {
            System.out.println(s);
        }
        return suggestionList;
    }


    /**
     * 新增商品：新增商品到mysql，同时更新到es文档
     * @param goods
     * @return
     */
    @PostMapping
    @ResponseBody
    public String save(Goods goods) {
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        goods.setCreateTime(time);
        goods.setUpdateTime(time);
        goods.setIsDeleted(0);
        Integer saveResult = goodsService.save(goods);
        if (saveResult > 0) {
            //将新增的goodsId发送到队列
            rabbitTemplate.convertAndSend(this.esGoodsExchange, this.esGoodsUpdateRoutingKey, goods.getGoodsId());
            System.out.println("新增成功！GoodsId："+goods.getGoodsId());
        } else {
            System.out.println("新增失败");
        }

        return "新增结果："+saveResult;
    }


    /**
     * 更新商品：更新商品到mysql，同时更新到es文档
     * @param goods
     * @return
     */
    @PutMapping
    @ResponseBody
    public String update(Goods goods) {
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        goods.setUpdateTime(time);
        Integer updateResult = goodsService.update(goods);
        if (updateResult > 0) {
            //将修改的goodsId发送到队列
            rabbitTemplate.convertAndSend(this.esGoodsExchange, this.esGoodsUpdateRoutingKey, goods.getGoodsId());
            System.out.println("更新成功！GoodsId："+goods.getGoodsId());
        } else {
            System.out.println("更新失败");
        }
        return "更新结果："+updateResult;
    }


    /**
     * 根据goodsId删除数据：同时删除es文档
     * @param goodsId
     * @return
     */
    @DeleteMapping("/{goodsId}")
    @ResponseBody
    public String delete(@PathVariable("goodsId") Integer goodsId) {
        Goods goods = new Goods();
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        goods.setGoodsId(goodsId);
        goods.setUpdateTime(time);
        goods.setIsDeleted(1);
        Integer deleteResult = goodsService.delete(goods);
        if (deleteResult > 0) {
            rabbitTemplate.convertAndSend(this.esGoodsExchange, this.esGoodsDeleteRoutingKey, goodsId);
            System.out.println("逻辑删除成功！GoodsId: "+goodsId);
        } else {
            System.out.println("逻辑删除失败");
        }
        return "逻辑删除结果："+deleteResult;
    }
}
